package com.example.gw_back_end.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.gw_back_end.domain.PageParam;
import com.example.gw_back_end.domain.PageResult;
import com.example.gw_back_end.domain.document.CartDocument;
import com.example.gw_back_end.domain.entities.Game;
import com.example.gw_back_end.domain.entities.Order;
import com.example.gw_back_end.domain.entities.OrderItem;
import com.example.gw_back_end.domain.entities.Warehouse;
import com.example.gw_back_end.mapper.GameMapper;
import com.example.gw_back_end.mapper.OrderItemMapper;
import com.example.gw_back_end.mapper.OrderMapper;
import com.example.gw_back_end.service.GameService;
import com.example.gw_back_end.service.OrderItemService;
import com.example.gw_back_end.service.OrderService;
import com.example.gw_back_end.service.WarehouseService;
import com.example.gw_back_end.service.mongodb.CartService;
import com.example.gw_back_end.utils.ThreadLocalUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    private final OrderMapper orderMapper;
    private final GameService gameService;
    private final GameMapper gameMapper;
    private final OrderItemMapper orderItemMapper;
    private final CartService cartService;
    private final WarehouseService warehouseService;

    public OrderServiceImpl(OrderMapper orderMapper, GameService gameService, OrderItemMapper orderItemMapper, CartService cartService, GameMapper gameMapper, WarehouseService warehouseService) {
        this.orderMapper = orderMapper;
        this.gameService = gameService;
        this.gameMapper = gameMapper;
        this.orderItemMapper = orderItemMapper;
        this.cartService = cartService;
        this.warehouseService = warehouseService;
    }

    // 新增订单(单游戏)
    @Override
    public boolean addOrder(Integer gameId) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Game game = gameService.getGameById(gameId);
        Order order = new Order();
        order.setUserId(userId);
        order.setOrderCode(UUID.randomUUID().toString());
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        order.setStatus(3);
        if (game.getPriceD().equals(BigDecimal.ZERO)) {
            order.setOrderTotalAmount(game.getPriceD());
        } else {
            order.setOrderTotalAmount(game.getPrice());
        }

        boolean orderResult = orderMapper.insert(order) > 0;
        boolean orderItemResult = false;

        if (orderResult) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getId());
            orderItem.setGameId(gameId);
            orderItemResult = orderItemMapper.insert(orderItem) > 0;
        }

        return (orderResult && orderItemResult);
    }

    // 新增订单(购物车多购)
    @Transactional
    @Override
    public boolean addOrderByCart() {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");

        // 获取用户购物车
        Optional<CartDocument> optionalCart = Optional.ofNullable(cartService.getShoppingCart());
        if (optionalCart.isEmpty() || optionalCart.get().getItems().isEmpty()) {
            throw new RuntimeException("购物车为空");
        }

        List<CartDocument.CartItem> cartItems = optionalCart.get().getItems();

        // 创建订单
        Order order = new Order();
        order.setUserId(userId);
        order.setOrderCode(UUID.randomUUID().toString());
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        order.setStatus(3);

        // 计算总金额
        BigDecimal totalAmount = cartItems.stream()
                .map(item -> {
                    BigDecimal priceD = item.getPriceD();
                    if (priceD != null && priceD.compareTo(BigDecimal.ZERO) > 0) {
                        return priceD;
                    } else {
                        return item.getPrice(); // fallback to price
                    }
                })
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        order.setOrderTotalAmount(totalAmount);

        int orderResult = orderMapper.insert(order);
        if (orderResult <= 0 || order.getId() == null) {
            throw new RuntimeException("订单创建失败");
        }

        // 插入订单项
        for (CartDocument.CartItem item : cartItems) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getId());
            orderItem.setGameId(Integer.valueOf(item.getGameId()));
//            orderItem.setQuantity(item.getQuantity());
            orderItemMapper.insert(orderItem);
        }

        // 清空购物车
        cartService.clearShoppingCart();

        return true;
    }


    // 删除订单
    @Override
    public boolean deleteOrder(Integer orderId) {
        return orderMapper.deleteById(orderId) > 0;
    }

    // 更新订单
    @Transactional
    @Override
    public boolean updateOrder(Order order) {
        if (order.getStatus().equals(3)) {
            LambdaQueryWrapper<OrderItem> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(OrderItem::getOrderId, order.getId());
            List<OrderItem> orderItems = orderItemMapper.selectList(queryWrapper);

            for (OrderItem orderItem : orderItems) {
                Warehouse warehouse = new Warehouse();
                warehouse.setUserId(order.getUserId()); // 建议字段名为 userId 而不是 id
                warehouse.setGameId(orderItem.getGameId());

                boolean saved = warehouseService.save(warehouse);
                if (!saved) {
                    return false; // 插入失败，直接返回 false
                }
            }
        }
        return orderMapper.updateById(order) > 0;
    }

    // 查询订单
    @Override
    public Order getOrderById(Integer orderId) {
        return orderMapper.selectById(orderId);
    }

    // 分页获取订单
    @Override
    public PageResult<Order> getAllOrders(PageParam pageParam,String clientType) {
        if(Objects.equals(clientType, "Client")){
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        LambdaQueryWrapper<Order> userQueryWrapper = new LambdaQueryWrapper<>();
        userQueryWrapper.eq(Order::getUserId, userId);
        Page<Order> orderPage = orderMapper.selectPage(new Page<>(pageParam.getPage(),pageParam.getSize()),userQueryWrapper);

        List<Order> records = orderPage.getRecords();

        for (Order order : records) {
            // 第一步：查询订单明细
            LambdaQueryWrapper<OrderItem> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(OrderItem::getOrderId, order.getId());
            List<OrderItem> orderItems = orderItemMapper.selectList(queryWrapper);

            // 提取 gameId 列表
            List<Integer> gameIds = orderItems.stream()
                    .map(OrderItem::getGameId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());

            // 第二步：查游戏详情
            if (!gameIds.isEmpty()) {
                List<Game> games = gameMapper.selectBatchIds(gameIds);
                order.setOrderItems(games);
            } else {
                order.setOrderItems(Collections.emptyList());
            }
        }

        return PageResult.setPageResult(orderPage);
        } else if(Objects.equals(clientType, "Vendor")) {
            return null;
        } else {
            Page<Order> orderPage = orderMapper.selectPage(new Page<>(pageParam.getPage(),pageParam.getSize()),null);
            List<Order> records = orderPage.getRecords();

            for (Order order : records) {
                // 第一步：查询订单明细
                LambdaQueryWrapper<OrderItem> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(OrderItem::getOrderId, order.getId());
                List<OrderItem> orderItems = orderItemMapper.selectList(queryWrapper);

                // 提取 gameId 列表
                List<Integer> gameIds = orderItems.stream()
                        .map(OrderItem::getGameId)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList());

                // 第二步：查游戏详情
                if (!gameIds.isEmpty()) {
                    List<Game> games = gameMapper.selectBatchIds(gameIds);
                    order.setOrderItems(games);
                } else {
                    order.setOrderItems(Collections.emptyList());
                }
            }

            return PageResult.setPageResult(orderPage);
        }
    }
}
